# coding=utf-8
import json
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseNotFound, HttpResponse, Http404
from django.shortcuts import render, redirect
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from account.models import User
from team.forms import ChangeTeamForm, InvitationForm, NewMemberJoinForm, JoinForm
from team.models import Team, Invitation, TeamMemberShip


@login_required
def view(request, id):
    try:
        term = Team.objects.get(id=id)
    except Team.DoesNotExist:
        raise Http404
    return render(request, 'team/view.html')


@login_required
def setting(request, team_id):
    try:
        team = Team.objects.get(id=team_id)
    except Team.DoesNotExist:
        raise Http404

    _assert_admin_team(request, team)

    if request.method == 'POST':
        form = ChangeTeamForm(instance=team, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('team_setting', id)
    else:
        form = ChangeTeamForm(instance=team)

    context = {
        'title': u'团队 - ' + team.name,
        'form': form,
        'team': team,
        'can_admin': request.user.can_admin_team(team),
        'invitation_form': InvitationForm(team),
        'memberships': team.teammembership_set.select_related('member'),
        'invitations': team.invitation_set.filter(),
    }
    return render(request, 'team/setting.html', context)


@login_required
@require_POST
@never_cache
def invite(request, team_id):
    try:
        team = Team.objects.get(id=team_id)
    except Team.DoesNotExist:
        raise Http404

    _assert_admin_team(request, team)

    form = InvitationForm(team, request.POST)
    if form.is_valid():
        invitations = form.save()
        data = []
        for invitation in invitations:
            data.append({
                'email': invitation.email,
                'token': invitation.token,
            })
        response = json.dumps({'success': True, 'data': data})
    else:
        response = json.dumps({'success': False, 'message': form.errors.get('emails')})
    return HttpResponse(response, content_type='text/json')


@login_required
@require_POST
@never_cache
def invitation_delete(request, token):
    try:
        invitation = Invitation.objects.get(token=token)
    except Invitation.DoesNotExist:
        raise Http404

    _assert_admin_team(request, invitation.team)

    invitation.delete()
    return HttpResponse(json.dumps({'success': True}), content_type='text/json')


def join(request, token):
    try:
        invitation = Invitation.objects.get(token=token)
    except Invitation.DoesNotExist:
        raise Http404

    try:
        member = User.objects.get(email=invitation.email)
    except User.DoesNotExist:
        form_class = NewMemberJoinForm
        template = 'team/new_member_join.html'
    else:
        if TeamMemberShip.objects.filter(member=member, team=invitation.team).exists():
            return redirect('team_view', invitation.team.pk)
        form_class = JoinForm
        template = 'team/join.html'

    if request.method == 'POST':
        form = form_class(invitation, request, request.POST)
        if form.is_valid():
            form.save()
            return redirect('team_view', invitation.team.pk)
    else:
        form = form_class(invitation)

    context = {
        'title': u'加入 ' + invitation.team.name,
        'form': form,
    }

    return render(request, template, context)


@login_required
@require_POST
@never_cache
def change_role(request, ship_id, action='upgrade'):
    try:
        ship = TeamMemberShip.objects.get(id=ship_id)
    except TeamMemberShip.DoesNotExist:
        raise Http404

    _assert_admin_team(request, ship.team)

    ship.role = 'admin' if action == 'upgrade' else 'general'
    ship.save()
    return HttpResponse(json.dumps({'success': True}), content_type='text/json')


@login_required
@require_POST
@never_cache
def remove_member(request, ship_id):
    try:
        ship = TeamMemberShip.objects.get(id=ship_id)
    except TeamMemberShip.DoesNotExist:
        raise Http404

    _assert_admin_team(request, ship.team)

    ship.delete()
    return HttpResponse(json.dumps({'success': True}), content_type='text/json')


def _assert_admin_team(request, team):
    if not request.user.can_admin_team(team):
        raise PermissionDenied

